﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using KPIS.GERP.GHRMS.APP.Classes;
using KPIS.GERP.GHRMS.BLL;
using KPIS.GERP.GHRMS.IBLL;
using KPIS.GERP.GHRMS.MODEL;
using Telerik.Web.UI;

namespace KPIS.GERP.GHRMS.APP.App_UI.UserControls
{
	public partial class PS_HisHealthCheck : System.Web.UI.UserControl
	{
		public object DataItem { get; set; }
		private string roundTypePrivate;
		private readonly IHisHealthCheckBLL hhcBll = new HisHealthCheckBLL();
		private readonly Main main = new Main();
		private readonly SsMng ssMng = new SsMng();

		protected void Page_Init(object sender, EventArgs e)
		{
			SetComboboxYearData();
            round_date.SetValue(DateTime.Now);
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if (DataItem == null) return;

		    SetComboboxYearData(Convert.ToString(DataBinder.Eval(DataItem, "RoundYear")));
			RoundType = Session["round_type"].ToString().EndsWith("Roundly") ? "Roundly" : "Yearly";// Convert.ToString(DataBinder.Eval(DataItem, "RoundType"));
			body_weight.Text = Convert.ToString(DataBinder.Eval(DataItem, "BodyWeight"));

			ButtonUpdate_.Visible = !(DataItem is GridInsertionObject);
			submitInsert_.Visible = (DataItem is GridInsertionObject);
		}

		public string RoundType
		{
			get { return round_number.Visible ? "Roundly" : "Yearly"; }
			set
			{
				roundTypePrivate = value;
				switch (roundTypePrivate)
				{
					case "Roundly":
						round_number.Visible = true;
						labelRoundNumber.Visible = true;
						lblHeader.Text = "การตรวจสุขภาพราย 6 เดือน";
						round_type.Value = "Roundly";
						break;
					case "Yearly":
					default:
						round_number.Visible = false;
						labelRoundNumber.Visible = false;
						lblHeader.Text = "การตรวจสุขภาพรายปี";
						round_type.Value = "Yearly";
						break;
				}
			}
		}
		 
		protected void submitInsert_Click(object sender, EventArgs e)
		{
		    List<string> errorStrings;
            if (!ValidatePass(out errorStrings))
		    {
		        main.MessageAlert(Page,string.Join(",", errorStrings.ToArray()));
		        return;
		    }
			try
			{
				hhcBll.Insert(new HisHealthCheckInfo
					{
						EmpSeq = Convert.ToInt32(Session["emp_seq"].ToString()),
						RoundType = RoundType,
						RoundDate = round_date.GetDateValue(),
						RoundNumber = main.ConvertNullInt(round_number.Value),
						Remark = remark.Text,
						RecordStatus = SystemInfo._ActiveRecordStatus,
						RoundYear = Convert.ToInt32(round_year.SelectedValue),
						CreatedBy = ssMng.UserSeqI,
						CreatedWhen = DateTime.Now,
						UpdatedBy = ssMng.UserSeqI,
						UpdatedWhen = DateTime.Now,
						BodyHeight = main.ConvertNullDecimal(body_height.Text),
						BodyWeight = main.ConvertNullDecimal(body_weight.Text),
						HealthAlk = main.ConvertNullDecimal(health_Alk.Text),
						HealthAltOrS6Pt = main.ConvertNullDecimal(health_ALT_or_S6PT.Text),
						HealthAstOrS6Ot = main.ConvertNullDecimal(health_AST_or_S6OT.Text),
						HealthCholestoral = main.ConvertNullDecimal(health_Cholestoral.Text),
						HealthCk6 = health_CK6_.Checked,
						HealthCricAcid = main.ConvertNullDecimal(health_Cric_Acid.Text),
						HealthLdl = main.ConvertNullDecimal(health_LDL.Text),
						HealthCxk = health_CXK_.Checked,
						HealthGlocox = main.ConvertNullDecimal(health_Glocox.Text),
						HealthHct = main.ConvertNullDecimal(health_HCT.Text),
						HealthPit = main.ConvertNullDecimal(health_PIT.Text),
                        HealthT6 = main.ConvertNullDecimal(health_T6.Text),
                        HealthHdl = main.ConvertNullDecimal(health_HDL.Text),
                        HealthBunCr = main.ConvertNullDecimal(health_HealthBunCr.Text)
					});
				main.MessageAlert(Page, "บันทึกข้อมูลแล้ว");
			}
			catch (Exception ex)
			{ 
                main.MessageAlert2(Page, ex, "PS_HisHealthCheck.ascx.cs/submitInsert_Click, Round Date = " + round_date.GetStringValue());
			}
		}

		protected void ButtonUpdate_Click(object sender, EventArgs e)
        {
            List<string> errorStrings;
            if (!ValidatePass(out errorStrings))
            {
                main.MessageAlert(Page, string.Join(",", errorStrings.ToArray()));
                return;
            }
			try
			{
				hhcBll.Update(new HisHealthCheckInfo
					{
						HealthCheckSequence = Convert.ToInt32(health_check_seq.Value),
						EmpSeq = Convert.ToInt32(Session["emp_seq"].ToString()),
						RoundType = RoundType,
						RoundDate = round_date.GetDateValue(),
						RoundNumber = main.ConvertNullInt(round_number.Value),
						Remark = remark.Text,
						RecordStatus = SystemInfo._ActiveRecordStatus,
						RoundYear = Convert.ToInt32(round_year.SelectedValue),
						UpdatedBy = ssMng.UserSeqI,
						UpdatedWhen = DateTime.Now,
						BodyHeight = main.ConvertNullDecimal(body_height.Text),
						BodyWeight = main.ConvertNullDecimal(body_weight.Text),
						HealthAlk = main.ConvertNullDecimal(health_Alk.Text),
						HealthAltOrS6Pt = main.ConvertNullDecimal(health_ALT_or_S6PT.Text),
						HealthAstOrS6Ot = main.ConvertNullDecimal(health_AST_or_S6OT.Text),
						HealthCholestoral = main.ConvertNullDecimal(health_Cholestoral.Text),
						HealthCk6 = health_CK6_.Checked,
						HealthCricAcid = main.ConvertNullDecimal(health_Cric_Acid.Text),
						HealthLdl = main.ConvertNullDecimal(health_LDL.Text),
						HealthCxk = health_CXK_.Checked,
						HealthGlocox = main.ConvertNullDecimal(health_Glocox.Text),
						HealthHct = main.ConvertNullDecimal(health_HCT.Text),
						HealthPit = main.ConvertNullDecimal(health_PIT.Text),
						HealthT6 = main.ConvertNullDecimal(health_T6.Text),
                        HealthHdl = main.ConvertNullDecimal(health_HDL.Text),
                        HealthBunCr = main.ConvertNullDecimal(health_HealthBunCr.Text)
					});
				main.MessageAlert(Page, "บันทึกข้อมูลแล้ว");
			}
			catch (Exception ex)
			{
				main.MessageAlert2(Page, ex, "PS_HisHealthCheck.ascx.cs/submitInsert_Click, Round Date = " + round_date.GetStringValue());
			}
		}

		#region Validate Form
		private bool ValidatePass(out List<string> errorStrings )
		{
            errorStrings = new List<string>();
			if (String.IsNullOrEmpty(round_date.GetStringValue()))
				errorStrings.Add("กรุณากรอกวันที่ตรวจ");
			if(round_number.Visible && round_number.Value ==null)
				errorStrings.Add("กรุณากรอกเลขครั้ง");
			if(round_year.SelectedValue ==null)
				errorStrings.Add("กรุณาเลือกปี");

			lblErrorValidate.Text = String.Join(Environment.NewLine, errorStrings.ToArray());

			return !(errorStrings.Count > 0);
		}
		#endregion Validate Form

		#region Setting ComboboxYear
		private int? YearFilter
		{
			get { return main.ConvertNullInt(round_year.SelectedValue); }
		}
		private void SetComboboxYearData(string s = null)
		{
		    string currenctSelected;
		    if (string.IsNullOrEmpty(s) && string.IsNullOrEmpty(round_year.SelectedValue))
		    {
		        currenctSelected = "" + CurrentYearBuddhist;
            }
            else if (string.IsNullOrEmpty(s) )
            {
                currenctSelected = round_year.SelectedValue;
            }
            else 
            {
                currenctSelected = s;
            } 

		    if (round_year.Items.Count == 0)
		    {
		        int yearStart = CurrentYearBuddhist - 20;
		        int yearEnd = CurrentYearBuddhist + 20;
		        for (int i = yearStart; i < yearEnd; i++)
		        {
		            round_year.Items.Add(new RadComboBoxItem(Convert.ToString(i), Convert.ToString(i))
		            {
		                Selected = ("" + i == currenctSelected)
		            });
		        }
		    }
		    else
		    {
		        round_year.SelectedValue = currenctSelected;
		    }
		}

		private void SetComboboxYearSelected(string selectedValue)
		{
			if (String.IsNullOrEmpty(selectedValue))
				round_year.SelectedValue =CurrentYearBuddhist.ToString();
			else if (round_year.Items.FindItemByValue(selectedValue) != null)
				round_year.SelectedValue = selectedValue;
			else
				round_year.Items.Add(new RadComboBoxItem(selectedValue, selectedValue) {Selected = true});
		}

		private int CurrentYearBuddhist
		{
			get { return new ThaiBuddhistCalendar().GetYear(DateTime.Now); }
		}
		#endregion Setting ComboboxYear
	}
}